from rest_framework import serializers
from .models import User
from rest_framework_jwt.settings import api_settings


class CreateUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label='确认密码', write_only=True)
    token = serializers.CharField(label='令牌', read_only=True)

    def validate(self, attrs):
        """数据验证"""
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('俩次的密码不相同')
        if attrs['name'] is None:
            raise serializers.ValidationError('昵称还没写那')
        return attrs

    def create(self, validated_data):
        """创建用户"""
        # 删除属性
        del validated_data['password2']
        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        # 令牌
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user

    class Meta:
        model = User
        fields = ('id', 'email', 'password', 'password2', 'name', 'token')
        extra_kwargs = {
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '密码长度请设置8-20位',
                    'max_length': '密码长度请设置88-20位'
                }
            },
        }


class UserDetailSerializer(serializers.ModelSerializer):
    """用户详情"""

    class Meta:
        model = User
        fields = ('id', 'name', 'email', 'head_path', 'signature', 'password', 'privacy')


class TestSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'name', 'create_time')
